package cn.restcloud.example.controller.mongo;

import cn.restcloud.framework.core.annotation.bean.BeanConfig;
import cn.restcloud.framework.core.annotation.bean.BeanType;
import cn.restcloud.framework.core.annotation.rest.MethodType;
import cn.restcloud.framework.core.annotation.rest.Param;
import cn.restcloud.framework.core.annotation.rest.Params;
import cn.restcloud.framework.core.annotation.rest.RestConfig;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.bson.Document;
import cn.restcloud.framework.core.base.PageRequestParams;
import cn.restcloud.framework.core.util.JsonUtil;
import cn.restcloud.framework.core.util.RequestUtil;
import cn.restcloud.framework.core.util.db.mongo.MongoPageUtil;
import cn.restcloud.framework.dm.dao.IModelDocDao;
import cn.restcloud.framework.dm.model.P_ModelConfigEntry;
import cn.restcloud.framework.dm.service.ModelDaoFactory;
import cn.restcloud.framework.view.base.DocAndView;
import cn.restcloud.framework.view.util.ViewUtil;

/**
 * MongoDb通用服务提供类示例,使用系统Dao操作实现数据的CRUD
 * 使用本类发布服务的优势是业务模型中列的事件均有效
 * @author Administrator
 *
 */

@BeanConfig(appId = "example",beanId = "MongoControllerRest",beanName = "通用服务提供类示例",beanType = BeanType.CONTROLLER,autowired = false,singleton = true,hotMode = true)
@RestConfig(url = "/rest/example/common")
public class MongoControllerRest {
	private String modelId="example.userList";
	IModelDocDao dao;
	
	public MongoControllerRest() throws Exception{
		//根据Modelid的配置动态获取通用Dao实现类
		dao=ModelDaoFactory.getModelDocDao(this.modelId);
	}
	
	@RestConfig(configName = "列出数据模型的所有记录",method = MethodType.GET,url = "/listAll")
	public DocAndView listAll()throws Exception{
		List<Document> docs=dao.listAll(modelId);
		DocAndView dv=ViewUtil.getJsonView(docs);
		return dv;
	}
	
	@RestConfig(configName = "分页列出数据模型的记录",method = MethodType.GET,url = "/listByPage")
	@Params({
		@Param(id = "PageNo", name = "当前页兼容page"),
		@Param(id = "pageSize", name = "每页显示数兼容rows"),
		@Param(id = "filters", name = "动态过滤条件",sampleValue="{\"fieldName\":\"value\"}"),
		@Param(id = "searchFilters", name = "动态搜索条件",sampleValue="{\"title\":\"test\",\"content\":\"test\"}"),
		@Param(id = "sort", name = "动态排序字段"),
		@Param(id = "order", name = "排序方向",sampleValue="ASC|DESC")
	})
	public DocAndView listByPage()throws Exception{
		
		//从url中传入的参数或者在代码中指定相关参数
		PageRequestParams urlParams=MongoPageUtil.getPageRequestParams();
		String urlPageNo=urlParams.getPageNo();//从url请求中获取参数
		String urlPageSize=urlParams.getPageSize();//从url请求中获取参数
		String orderById=urlParams.getSort(); //从url请求中获取排序字段
		String sortDirection=urlParams.getOrder(); //从url请求中获取排序方式ASC升序,降序DESC
		String urlFilters=urlParams.getFilters(); //从url请求中获取动态的过虑条件JSON字符串:{"dbType":"M,D,R","appId":"core"}解析后为(dbType='M' or dbType='D' or dbType='R') and (appId='core')
		String urlSearchFilters=urlParams.getSearchFilters(); //JSON字符串格式:{"title":"test","content":"test"}解析后为:(title like '%test%' or content like '%test%')
		String defaultFilters=""; //格式:Filters.or(Filters.eq("userid","admin"),Filters.eq("userid","test"))
		
		//从url获取分页信息，以url中传入的为优先
		int pageNo=1,pageSize=20;
		if(StringUtils.isNotBlank(urlPageNo)){
			pageNo=Integer.parseInt(urlPageNo); //当前第几页
		}
		if(StringUtils.isNotBlank(urlPageSize)){
			pageSize=Integer.parseInt(urlPageSize); //每页显示数
		}

		//实体模型排序字段不能为空
		P_ModelConfigEntry modelConfig=ModelDaoFactory.getModelConfig(modelId);
		if(modelConfig.getModelType().equals("E") && StringUtils.isBlank(orderById)){
			return ViewUtil.getErrorView("实体模型分页时orderById不能为空!");
		}
		
		//使用url中动态传入的条件进行分页
		String jsonStr=dao.listByPage(modelId,defaultFilters,urlFilters,urlSearchFilters,orderById,sortDirection,pageNo,pageSize).toJson();
		
		//自定义条件分页，Filters可以自已组合格式为:Filters.or(Filters.eq("userid","admin"),Filters.eq("userid","test"))
//		String jsonStr=dao.listByPage(modelId,Filters,orderById,sortDirection,pageNo,pageSize).toJson(); 
		DocAndView dv=ViewUtil.getJsonView(jsonStr);
		
		return dv;
	}
	

	@RestConfig(configName = "根据filters过虑条件返回多条数据记录",method = MethodType.GET,url = "/listByFilters")
	public DocAndView listByFilters()throws Exception{
		String filters="Filters.eq(\"userId\",\"admin\")";//格式：Filters.and(Filters.eq("id","001"),Filters.eq("id","002"))
		List<Document> listDocs=dao.listByFilters(modelId,filters);
		return ViewUtil.getJsonView(listDocs);
	}
	
	@RestConfig(configName = "根据filters过虑条件返一条数据记录",method = MethodType.GET,url = "/getByFilters")
	public DocAndView getByFilters()throws Exception{
		String filters="Filters.and(Filters.eq(\"userId\",\"admin\"),Filters.eq(\"age\",882))"; //过滤条件示例:{"filters":"id='{id}' or appId='core'"}期中{id}可以从url中传入
		Document doc=dao.getByFilters(modelId,filters);
		String jsonStr=JsonUtil.doc2Json(doc); //转为json字符串
		DocAndView dv=ViewUtil.getJsonView(jsonStr);
		
		return dv;
	}
	
	@RestConfig(configName = "根据id获查询数据记录",method = MethodType.GET,url = "/getById")
	@Params({
		@Param(id = "id", name = "唯一id",required=true)
	})
	public DocAndView getById()throws Exception{
		String id=RequestUtil.getString("id"); //数据记录的唯一id
		Document doc=dao.getById(modelId, id);
		String jsonStr=JsonUtil.doc2Json(doc);
		DocAndView dv=ViewUtil.getJsonView(jsonStr);
		return dv;
	}
	
	@RestConfig(configName = "把POST的数据保存或更新到数据模型中",method = MethodType.POST,url = "/save")
	@Params({
		@Param(id = "RequestBody", name = "JSON字符串",type="{modelId}")
	})
	public DocAndView saveRequestBody()throws Exception{
		//把所有请求数据对应存入到数据模型中，系统根据id唯一字段进行判断是更新还是插入
		dao.save(modelId,RequestUtil.getContextDocument());
		DocAndView dv=ViewUtil.getSuccessView("1");
		return dv;
	}
	
	@RestConfig(configName = "根据ids参数删除数据模型中对应的多条记录",method = MethodType.POST,url = "/delete")
	@Params({
		@Param(id = "ids", name = "唯一ids多个用逗号分隔",required=true)
	})
	public DocAndView deleteByIds()throws Exception{
		String _ids=RequestUtil.getString("ids"); //数据记录的id
		int i=dao.deleteByIds(modelId, _ids);
		DocAndView dv=ViewUtil.getSuccessView(String.valueOf(i));
		return dv;
	}
	
	@RestConfig(configName = "根据过滤条件删除数据模型中对应的多条记录",method = MethodType.POST,url = "/deleteByFilters")
	public DocAndView deleteByFilters()throws Exception{
		String filters=""; //格式:Filters.or(Filters.eq("id","1"),Filters.eq("id","2"))
		int i=dao.deleteByFilters(modelId, filters);
		DocAndView dv=ViewUtil.getSuccessView(String.valueOf(i));
		
		return dv;
	}
	
	
}
